package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存阅读行为
     * 1. 阅读行为不需要回显和查询, 所以不需要保存到redis, 直接保存到数据库即可
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1.效验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录用户id，判断是否登录
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.游客身份不能进行以下操作
        if (apUser.getId() == 0) {
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }
        //4.查询mongo中是否有数据，如果有，则更新次数，否则新增
        Criteria criteria=new Criteria().orOperator(Criteria.where("userId").is(apUser.getId())
                ,new Criteria().orOperator(Criteria.where("userId").is(apUser.getId())),Criteria.where("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(Query.query(criteria), ApReadBehavior.class);
        /*ApReadBehavior readBehavior = mongoTemplate.findOne(
                Query.query(Criteria.where("userId").is(apUser.getId())
                        .and("articleId").is(dto.getArticleId()))
                , ApReadBehavior.class);*/
        if (readBehavior == null) {
            //4.新增mongo
            readBehavior = new ApReadBehavior();
            BeanUtils.copyProperties(dto, readBehavior);
            readBehavior.setId(ObjectId.get().toHexString());
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setUserId(apUser.getId().longValue());
            readBehavior.setCount(1);
        } else {
            //更新操作，更新次数和时间
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setCount(dto.getCount()+ readBehavior.getCount());
        }
        mongoTemplate.save(readBehavior);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
